package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.exception.CustExcepiton;
import com.itheima.result.R;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")

    public R getMessage(@RequestBody User user, HttpSession httpSession) {
        String phone = user.getPhone();
        String s = ValidateCodeUtils.generateValidateCode4String(4);
//        httpSession.setAttribute("msg", s);
        redisTemplate.opsForValue().set(phone, s, 300, TimeUnit.SECONDS);
        return R.success(s);
    }

    @PostMapping("/login")
    public R getUserById(@RequestBody User user, HttpSession httpSession) {
//        String msg = (String) httpSession.getAttribute("msg");
        String phone = user.getPhone();
        String msg = (String) redisTemplate.opsForValue().get(phone);
        log.info(msg);
        String userMsg = user.getCode();
        if (!msg.equals(userMsg)) {
            throw new CustExcepiton("验证码错误");
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, user.getPhone());
        User one = userService.getOne(lqw);
        if (one == null) {
            user.setName(user.getPhone());
            userService.save(user);
            User one1 = userService.getOne(lqw);
            httpSession.setAttribute("user", one1);
            return R.success(one1);

        }
        httpSession.setAttribute("user", one);
        redisTemplate.delete(phone);
        return R.success(one);
    }
}
